package controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import model.Order;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;

import common.StringUtil;
import service.OrderService;

@Controller
@RequestMapping("morder")
public class OrderControler {
	@Autowired
	public OrderService orderService;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/list")
	public String list(
			Model model,
			HttpServletRequest request,
			@RequestParam(value = "pageNow", defaultValue = "1") String pageNow,
			@RequestParam(value = "pageRow", defaultValue = "10") String pageRow,
			@RequestParam(value = "orderid", required = false) String orderid) {

		int page = 1;
		int limit = 2;
		if ((pageNow != null) && (!"".equals(pageNow))) {
			page = Integer.parseInt(pageNow);
		}

		if ((pageRow != null) && (!"".equals(pageRow))) {
			limit = Integer.parseInt(pageRow);
		}

		PageBounds pageBounds = new PageBounds(page, limit);

		Map mapValue = new HashMap();
		mapValue.put("orderid", orderid);
		Map map = this.orderService.selectAll(pageBounds, mapValue);

		List list = (List) map.get("list");
		Paginator paginator = (Paginator) map.get("paginator");

		model.addAttribute("list", list);
		model.addAttribute("paginator", paginator);

		model.addAttribute("order", request.getSession().getAttribute("order"));
		model.addAttribute("orderid", orderid);

		return "order/list";
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("/detail")
	public String detail(Model model,
			@RequestParam(value = "orderid", required = false) String orderid) {
		Order order = orderService.getOrderDetail(orderid);

	    List imges = new ArrayList();
		if (!StringUtil.isEmpty(order.getPicShow())) {
			imges = Arrays.asList(order.getPicShow().split(","));
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		
		model.addAttribute("order", order);
		model.addAttribute("imges", imges);
		model.addAttribute("orderTime", sdf.format(new Date(Long.valueOf(order.getOrderTime()))));
		model.addAttribute("reserveTime", sdf.format(new Date(Long.valueOf(order.getReserveTime()))));
		model.addAttribute("finishTime", sdf.format(new Date(Long.valueOf(order.getFinishTime()))));
		model.addAttribute("commentTime", sdf.format(new Date(Long.valueOf(order.getCommentTime()))));

		return "order/detail";
	}
}
